﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using My.Core.Authorization.Requirement;
using My.Core.Constant;

namespace My.Core.Authorization.Provider
{
    /// <summary>
    /// 自定义授权策略
    /// </summary>
    public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider, IAuthorizationPolicyProvider
    {
        public AuthorizationPolicyProvider(IOptions<AuthorizationOptions> options) : base(options) { }

        public new Task<AuthorizationPolicy> GetDefaultPolicyAsync()
            => base.GetDefaultPolicyAsync();

        public new Task<AuthorizationPolicy?> GetFallbackPolicyAsync()
            => base.GetFallbackPolicyAsync();

        /// <summary>
        /// 返回给定授权名称的授权策略
        /// </summary>
        /// <param name="policyName">授权名称</param>
        /// <returns>返回的授权策略</returns>
        public new Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
        {
            if (policyName.StartsWith(Permissions.User))
            {
                var policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
                policy.AddRequirements(new PermissionAuthorizationRequirement(policyName));
                return Task.FromResult<AuthorizationPolicy?>(policy.Build());
            }
            return base.GetPolicyAsync(policyName);
        }
    }
}
